<template>
  <div class="app-container app-config">
    <el-form :model="queryParams" ref="queryForm" size="mini">
      <el-query-row :label="'产品'">
        <el-col :span="4">
          <el-form-item prop="appcode">
            <el-select
              v-model="queryParams.appcode"
              @change="_productChange"
              placeholder="产品"
              filterable
              clearable
              style="width: 100%">
              <el-option
                v-for="(item, index) in productList"
                :key="item + index"
                :label="item.name"
                :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="20">
          <el-form-item>
            <el-button @click="openAddConfig = true" type="primary">新增</el-button>
            <!-- <el-button @click="openBatchUpdate = true">批量调整支付宝配置</el-button> -->
            <!-- <el-button @click="openCopyConfig = true">复制配置</el-button> -->
            <!-- <el-button @click="openAuditConfig = true">开启/关闭审核配置</el-button> -->
            <!-- <el-button @click="openQuickClear = true">快捷清除</el-button> -->
            <!-- <el-button @click="openCheckConfig = true">校验配置</el-button> -->
          </el-form-item>
        </el-col>
      </el-query-row>
      <el-query-row :label="'渠道'">
        <el-col :span="24">
          <el-form-item>
            <el-button
            v-for="(item, index) in channelList"
            :key="item + index"
            :class="[item.value === queryParams.channel ? 'active' : '']"
            @click="_channelChange(item)">{{item.name}}</el-button>
          </el-form-item>
        </el-col>
      </el-query-row>
      <el-query-row :label="'类型'">
        <el-col :span="24">
          <el-form-item>
            <el-button
            v-for="(item, index) in appTypeList"
            :key="item + index"
            :class="[item.value === queryParams.type ? 'active' : '']"
            @click="_appTypeChange(item)">{{item.name}}</el-button>
          </el-form-item>
        </el-col>
      </el-query-row>
      <el-query-row :label="'key'">
        <el-col :span="24">
          <el-form-item>
            <el-button
              v-for="(item, index) in configKeyList"
              :key="item + index"
              :class="[item.value === queryParams.key ? 'active' : '']"
              @click="_configKeyChange(item)"
              style="margin-bottom: 10px;">{{item.name}}</el-button>
          </el-form-item>
        </el-col>
      </el-query-row>
    </el-form>
    <el-form :model="form" :rules="formRule" ref="form" size="mini">
      <el-query-row :label="'默认'" :labelWidth="100">
        <el-col :span="10">
          <el-form-item prop="default">
            <!-- <el-input v-model="form.default" /> -->
            <el-switch v-if="form.default"
          style="display: block"
          v-model="form.default"
          active-color="#13ce66"
          inactive-color="#ff4949"
          active-value="1"
          inactive-value="0">
        </el-switch>
          </el-form-item>
        </el-col>
      </el-query-row>
      <el-query-row :label="'版本'" :labelWidth="100">
        <el-col :span="5">
          <el-form-item prop="version">
            <el-input v-model="form.version" />
          </el-form-item>
        </el-col>
           <el-col :span="5" style="font-color:#c0c0c0;font-size:12px;height:28px;line-height:28px;">多个用,号隔开,例如:1.0.0,1.0.1,1.0.2

           </el-col>
        <el-col :span="13" style="text-align:right;">
          <el-form-item>
            <el-button @click="_saveConfig" type="primary">保存</el-button>
            <el-button @click="_delCurrConfig" type="warning">单版本删除</el-button>
            <el-button @click="_delAllConfig" type="danger">全部删除</el-button>
            <el-button @click="_addOneConfigHandle" type="info">新增单版本</el-button>
          </el-form-item>
        </el-col>
      </el-query-row>
      <el-query-row :label="'配置'" :labelWidth="100">
        <el-col :span="12">
          <el-form-item prop="jsonStr">
            <b-code-editor v-model="form.jsonStr" :indent-unit="2" :with="`${editHeight}px`" :height="`${editHeight}px`" style="border: #C0C4CC 1px solid;"  />
          </el-form-item>
        </el-col>
        <el-col :span="11">
          <el-form-item prop="jsonStr">
            <b-code-editor v-model="remark" :indent-unit="2"  :height="`${editHeight}px`" style="border: #C0C4CC 1px solid;" theme="duotone-light" readonly :auto-format="true" :line-wrap="true" :show-number="false"/>
          </el-form-item>
        </el-col>
      </el-query-row>
    </el-form>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="pageNum"
      :limit.sync="pageSize"
      :pageSizes="[1]"
      @pagination="getList"
    />
    <addConfig :open.sync="openAddConfig" :callback="_addAppConfigCallback" />
    <!-- <batchUpdate :open.sync="openBatchUpdate" /> -->
    <!-- <copyConfig :open.sync="openCopyConfig" /> -->
    <!-- <auditConfig :open.sync="openAuditConfig" /> -->
    <!-- <quickClear :open.sync="openQuickClear" /> -->
    <addOneConfig :open.sync="openAddOneConfig" :callback="_addOneConfigCallback" />
    <!-- <checkConfig :open.sync="openCheckConfig" /> -->
  </div>
</template>

<script>
import { getAllAppList, getConfig, saveOrUpdateConfig, delConfig } from '@/api/configs/appConfig.js'
import addConfig from './addConfig.vue'
// import batchUpdate from './batchUpdate.vue'
// import copyConfig from './copyConfig.vue'
// import auditConfig from './auditConfig.vue'
// import quickClear from './quickClear.vue'
import addOneConfig from './addOneConfig.vue'
// import checkConfig from './checkConfig.vue'

export default {
  components: {
    'addConfig': addConfig,
    // 'batchUpdate': batchUpdate,
    // 'copyConfig': copyConfig,
    // 'auditConfig': auditConfig,
    // 'quickClear': quickClear,
    'addOneConfig': addOneConfig,
    // 'checkConfig':checkConfig
  },
  data () {
    return {
      remark:'配置说明',
      queryParams: {
        appcode: '',
        channel: '',
        type: null,
        key: '',
        defaultConfig: '',
        version: '',
        value: ''
      },
      productList: [],
      channelList: [],
      appTypeList: [{name: '应用内', value: 0} ],
      configKeyList: [],
      form: {
        default: 0,
        version: '',
        textarea: '',
        jsonStr: ''
      },
      formRule: {
        default: [{ required: true, message: '必填项', trigger: 'blur' }],
        version: [{ required: true, message: '必填项', trigger: 'blur' }],
      },
      currConfig: {},
      valueList: [],
      pageNum: 1,
      pageSize: 1,
      total: 1,
      editHeight: window.innerHeight - 450,
      openAddConfig: false,
      // openBatchUpdate: false,
      // openCopyConfig: false,
      // openAuditConfig: false,
      // openQuickClear: false,
      openAddOneConfig: false,
      // openCheckConfig:false
    }
  },
  created () {
    this._getProductList()
  },
  mounted () {},
  watch: {
    'form.default' (newValue) {
      this.valueList[this.pageNum - 1].default = newValue;
    },
    'form.version' (newValue) {
      this.valueList[this.pageNum - 1].version = newValue;
    },
    'form.textarea' (newValue) {
      try {
        if(JSON.parse(newValue.trim())) {
          this.form.jsonStr = JSON.stringify(JSON.parse(newValue),null,2)
        }
      } catch (e) {
        console.log(`JSON格式错误，不予转换`);
        this.form.jsonStr = `{}`;
      }
    },
    'form.jsonStr' (newValue) {
      let value = newValue.replace(/[ ]|[\r\n]/g, '')
      try {
        if (JSON.parse(value)) {
          this.valueList[this.pageNum - 1].value = JSON.parse(value);
        }
      } catch (error) {
        console.log(`JSON格式错误，不予保存`);
      }
    },
  },
  methods: {
    _saveConfig () {
      let vm = this;
      let { value, ...params } = vm.currConfig;
      params.value = JSON.stringify(vm.valueList);
      params.type = vm.queryParams.type;
      saveOrUpdateConfig(params).then(response => {
        if (response.code === 200) {
          vm.$modal.msgSuccess('操作成功');
          vm._getConfig();
        } else {
          vm.$modal.msgError(response.msg);
        }
      })
    },
    _delCurrConfig () {
      let vm = this;
      vm.$modal.confirm('是否确认删除当前配置？').then(() => {
        let newValueList = vm.valueList.filter((item, index) => {
        return index !== (vm.pageNum - 1);
        });
        vm.valueList = newValueList;
        vm.total = 0;
        vm._saveConfig();
      });
    },
    _delAllConfig () {
      let vm = this;
      vm.$modal.confirm('是否确认删除所有配置？').then(() => {
        vm.loading = true;
        return delConfig({ id: vm.currConfig.id, type: vm.queryParams.type });
      }).then(response => {
        if (response.code === 200) {
          vm.$modal.msgSuccess('操作成功');
          vm._clearData(3);
        } else {
          vm.$modal.msgError(response.msg);
        }
      }).catch(() => {
        vm.loading = false;
      });
    },
    _addOneConfigCallback (item) {
      let vm = this;
      vm.valueList.push(item);
      vm.total = 0;
      vm._saveConfig();
    },
    _addAppConfigCallback (item) {
      let vm = this;
      vm._getProductList();
      vm._getChannelList();
    },
    getList () {
      let vm = this;
      if (vm.valueList.length) {
        let currItem = vm.valueList[vm.pageNum - 1];
        vm.form.default = currItem.default;
        vm.form.version = currItem.version;
        vm.form.textarea = JSON.stringify(currItem.value);
      } else {
        vm.form = {
          default: 0,
          version: '',
          textarea: '',
          jsonStr: ''
        }
      }
    },
    _getConfig () {
      let vm = this
      getConfig(vm.queryParams).then(response => {
        if (response.code === 200) {
          vm.currConfig = response.data;
          vm.valueList = response.data.valueList;
          vm.pageNum = 1;
          vm.total = response.data.valueList.length;
          vm.remark=response.data.remark?response.data.remark:'配置说明';
          vm.getList();
        }
      })
    },
    _getProductList () {
      getAllAppList().then(response => {
        this.productList = response.data.map(item => {
          return {
            name: item.appname,
            value: item.appcode,
            channelList: item.channelList
          }
        })
      })
    },
    _productChange () {
      this._clearData(3)
      this._getChannelList()
    },
    _getChannelList () {
      let vm = this
      let currItem = vm.productList.filter(item => {
        return item.value === vm.queryParams.appcode
      })[0]
      vm.channelList = currItem.channelList.map(item => {
        return {
          name: item.channel,
          value: item.channel,
          innerList: item.innerList,
        }
      })
    },
    _channelChange (item) {
      let vm = this
      vm.queryParams.channel = item.value
      vm._clearData(2)
    },
    _appTypeChange (item) {
      let vm = this
      vm.queryParams.type = item.value
      vm._clearData(1)
      vm._getConfigKey()
    },
    _getConfigKey () {
      let vm = this
      let currItem = vm.channelList.filter(item => {
        return item.value === vm.queryParams.channel
      })[0]
      let typeConfig = {
        0: 'innerList',
        1: 'outList'
      }
      vm.configKeyList = currItem[typeConfig[vm.queryParams.type]] ? currItem[typeConfig[vm.queryParams.type]].map(item => {
        return {
          name: item.name,
          value: item.key
        }
      }) : []
    },
    _configKeyChange (item) {
      let vm = this
      vm.queryParams.key = item.value
      vm._getConfig()
    },
    _addOneConfigHandle () {
      let vm = this;
      if (vm.currConfig.id) {
        vm.openAddOneConfig = true;
      } else {
        vm.$modal.msgError('请先选择配置后再进行此操作');
      }
    },
    _clearData (level) {
      let vm = this
      let keyArr = ['key', 'type', 'channel']
      for (let i = 0; i < level; i++) {
        vm.queryParams[keyArr[i]] = null
      }
      vm.configKeyList = [];
      vm.currConfig = {};
      vm.valueList = [];
      vm.form = {
        default: 0,
        version: '',
        textarea: '',
        jsonStr: ''
      };
    }
  },
}
</script>

<style lang="scss">
.app-config {
  .el-query-row {
    .el-query-content {
      .el-button {
        &.active {
          color: white;
          background: #409eff;
          border-color: #409eff;
        }
      }
    }
  }
  .CodeMirror {
    min-height: 300px;
    height: 100% !important;
  }
}
</style>
